<script setup>
import Toast from '@vant/weapp/dist/toast/toast';

import newLoading from '@/components/newLoading/index.vue';
import tgpTextarea from './child/tgpTextarea.vue'


import { usePaintingStore } from '@/store';
import { imgUploadVerify } from '@/utils/auth'
import { checkImageTransparency } from "@/utils/myCanvas";
import { getCategoryDetail } from '@/api/home'
import { editImgUpload, aiBackgroundUpload, imgAiBackground, getImageByTaskId } from '@/api/painting'
import { ref } from 'vue'
import { onLoad, onReady, onUnload } from '@dcloudio/uni-app'

const paintingStore = usePaintingStore()

// 页面携带参数
const queryItem = ref({})
// 查询详情信息
const queryInfo = ref({})
// 原始图片地址
const oldImageFileUrl = ref('')
// 页面参数
const queryParams = ref({})
// 提交数据
const queryData = ref({
  promptWeight: 0.5,
  model: 'TYWX',
  imgModel: 'TY-AiImgBackground',
  modelVersion: 'v3',
})
// 消耗算力
const expendNum = ref(0)
// 图片数量
const imgNumList = ref([])
// 文本域ref
const tgpareaRef = ref(null)

const loading = ref(false);
const loadingRef = ref(null);

// 任务ID
const taskId = ref('')
let timer = null

// 模型列表
const modelList = ref([])





// 设置提示词
function setPrompt(prompt) {
  tgpareaRef.value.setPrompt(prompt)
}



// 开始生成
async function startFn() {
  clearInterval(timer);
  queryData.value.prompt = tgpareaRef.value.getPromptInfo().prompt;
  tgpareaRef.value.setLocalSelectList();
  if (!queryData.value.prompt && !queryParams.value.refImageUrl) {
    return Toast.fail('请输入描述词或上传参考图片');
  }
  loading.value = true;
  await editImgUploadFn();
  if (queryParams.value.refImageUrl) {
    await aiBackgroundUploadFn();
  }
  imgAiBackgroundFn();
}


// 获取任务状态
async function getImageByTaskIdFn() {
  const res = await getImageByTaskId(taskId.value)
  if (res.data.state === 1) {
    clearInterval(timer);
    await loadingRef.value.completeLoading()
    const data = {
      id: res.data.id,
      title: queryInfo.value.title,
      modelTypeId: queryItem.value.modelTypeId,
    }
    uni.navigateTo({
      url: `/draw/paintingResultPage/index?item=${JSON.stringify(data)}`,
    });
  } else if (![3, 4].includes(res.data.state)) {
    clearInterval(timer);
    const errorMessage = res.data?.remark.split('失败原因：')[1] || res.data?.remark || '生成失败，请稍后再试'
    Toast.fail(errorMessage);
    loading.value = false
  }
}


// 发起背景生成任务
async function imgAiBackgroundFn() {
  try {
    queryData.value = Object.assign({}, queryParams.value, queryData.value)
    paintingStore.setGenerationBgcFn(queryData.value)
    const res = await imgAiBackground(queryData.value)
    taskId.value = res.data.taskId
    timer = setInterval(() => {
      getImageByTaskIdFn()
    }, 5000);
  } catch (error) {
    loading.value = false
  }

}




// 上传背景参考原图 
async function aiBackgroundUploadFn() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await aiBackgroundUpload(queryParams.value.refImageUrl, {
        orgImgUrl: queryData.value.imageFileUrl,
      })
      queryData.value.refImageUrl = res.data.refImgUrl
      resolve()
    } catch (error) {
      loading.value = false
      reject()
    }
  })
}



// 上传原图
async function editImgUploadFn() {
  return new Promise(async (resolve, reject) => {
    try {
      const res = await editImgUpload({
        type: 6,
        orgImg: queryParams.value.imageFileUrl
      })
      queryData.value.imageFileUrl = res.orgImgUrl
      resolve()
    } catch (error) {
      loading.value = false
      reject()
    }
  })
}



// 滑块点击
function sliderChange(e) {
  queryData.value.promptWeight = e.detail
}

// 滑块拖动
function sliderDrag(e) {
  queryData.value.promptWeight = e.detail.value
}



// 设置图片文件URL
function setImageFileUrl(url) {
  queryParams.value.imageFileUrl = url
}



// 前往图片处理
function imageProcessing() {
  const data = {
    imageFileUrl: oldImageFileUrl.value,
  }
  uni.navigateTo({
    url: `/newEditionDraw/imageProcessing/index?item=${JSON.stringify(data)}`
  })
}


// 删除背景参考图片
function delRefImageUrl() {
  queryParams.value.refImageUrl = ''
  queryData.value.refImageUrl = ''
}


// 上传背景参考图片
function uplodRefImgFn() {
  uni.chooseImage({
    count: 1,
    success(e) {
      queryParams.value.refImageUrl = e.tempFilePaths[0]
    }
  })
}



// 上传图片
async function uploadImgFn() {
  const res = await imgUploadVerify({
    format: 'png'
  })
  try {
    await checkImageTransparency(res)
    queryParams.value.imageFileUrl = res
    oldImageFileUrl.value = res
  } catch (error) {
    Toast.fail('请选择png格式的透明背景图')
  }
}


// 模型点击事件
function modelItemClick(e) {
  queryData.value.modelVersion = e.modelVersion
}



// 加载关闭事件
function loadingClose() {
  clearInterval(timer);
}


// 数据转换
function dataConversion() {
  queryInfo.value.categoryParam.forEach(item => {
    if (item.title === 'imgNum') {
      imgNumList.value = item.data[0].title.split(',')
      queryData.value.num = imgNumList.value[0]
    } else if (item.title === 'expendNum') {
      expendNum.value = item.data[0].title
    } else if (item.title === 'model') {
      modelList.value = item.data
      modelList.value.forEach(item => {
        item.label = item.title.split('-')[1]
        item.modelVersion = item.title.split('-')[0]
      })
      queryData.value.modelVersion = modelList.value[0].modelVersion
    }
  })
}

// 获取分类详情
async function getCategoryDetailFn() {
  const res = await getCategoryDetail(queryItem.value.id)
  queryInfo.value = res.data
  dataConversion()
}

onUnload(() => {
  clearInterval(timer);
  loading.value = false
})


onLoad((e) => {
  if (e.item) {
    queryItem.value = JSON.parse(e.item)
    queryData.value.modelType = queryItem.value.modelTypeId
  }
  getCategoryDetailFn()
})


defineExpose({
  setPrompt,
  setImageFileUrl,
})
</script>

<template>
  <div class='orgGenerationBgc'>
    <NavBar>{{ queryInfo?.title }}</NavBar>
    <div class="container">

      <div class="title_box">模型</div>
      <div class="modal_list">
        <div class="modal_item" :class="{ active: queryData.modelVersion === item.modelVersion }"
          v-for="item, index of modelList" :key="index" @click="modelItemClick(item)">
          {{ item.label }}
        </div>
      </div>

      <div class="title_box">上传图片</div>
      <div class="uploadImg" @click="uploadImgFn">
        <img v-if="queryParams.imageFileUrl" :src="queryParams.imageFileUrl" mode="heightFix" class="imgSty" alt="">
        <div class="upload_btn" v-else>
          <i class="iconfont ai-icon-shangchuancankaotu"></i>
          <div class="text">上传图片</div>
        </div>

        <div class="imageProcessing_btn" v-if="queryParams.imageFileUrl" @click.stop="imageProcessing">
          <div class="text">图片调整</div>
        </div>
      </div>

      <tgpTextarea ref="tgpareaRef" :imageFileUrl="oldImageFileUrl"></tgpTextarea>



      <div class="title_box">上传背景参考图
        <span class="text">（AI会在参考图基础上，进行绘制）</span>
      </div>
      <div class="uploadRefImg" @click="uplodRefImgFn">
        <img v-if="queryParams.refImageUrl" :src="queryParams.refImageUrl" mode="aspectFit" class="imgSty" alt="">
        <div class="upload_btn" v-else>
          <i class="iconfont ai-icon-shangchuancankaotu"></i>
        </div>

        <div class="delIcon_box" v-if="queryParams.refImageUrl" @click.stop="delRefImageUrl">
          <div class="delIcon">
            <i class="iconfont ai-icon-shanchutupian"></i>
          </div>
        </div>
      </div>



      <div class="label_box">
        <div class="label">参考程度</div>
        <div class="value">
          <van-slider :value="queryData.promptWeight" :step="0.1" :min="0.1" :max="1" active-color="#86CA8B"
            bar-height="6" use-button-slot @drag="sliderDrag" @change="sliderChange">
            <template #button>
              <div class="sliderBtn">{{ queryData.promptWeight }}</div>
            </template>
          </van-slider>
        </div>
      </div>
      <div class="sliderLabel">参考程度越高，则文字描述权重越低</div>




      <div class="title_box">选择生成张数</div>
      <div class="imgNumList">
        <div class="imgNum_item" :class="{ active: queryData.num === item }" v-for="item, index of imgNumList"
          :key="index" @click="queryData.num = item">
          {{ item }}
        </div>
      </div>
    </div>
    <div class="footer">
      <div class="footer_placeholder"></div>
      <div class="footer_content">
        <myDrawButton :expendNum="expendNum * queryData.num" @click="startFn"></myDrawButton>
      </div>
    </div>
  </div>
  <van-toast id="van-toast" />
  <newLoading ref="loadingRef" v-model="loading" :duration="12000" :label="['排队中，预计等待10秒']" @close="loadingClose">
  </newLoading>
</template>

<style lang='scss' scoped>
.orgGenerationBgc {
  .container {
    padding: 0 30rpx 30rpx;

    .title_box {
      font-size: 28rpx;
      color: var(--a-one-text-color);
      font-weight: bold;
      position: relative;
      padding-left: 30rpx;
      margin-top: 40rpx;
      margin-bottom: 18rpx;

      &::before {
        content: '';
        position: absolute;
        left: 0;
        top: 50%;
        transform: translate(0, -50%);
        width: 12rpx;
        height: 18rpx;
        background: var(--a-main-color);
        border-radius: 6rpx;
      }

      .text {
        font-size: 24rpx;
        font-weight: normal;
      }
    }

    .modal_list {
      display: flex;
      align-items: center;
      gap: 20rpx;

      .modal_item {
        box-sizing: border-box;
        width: 241rpx;
        height: 53rpx;
        font-size: 22rpx;
        color: var(--a-one-text-color);
        border-radius: 12rpx;
        border: 2rpx solid var(--a-main-box-bg-color);
        display: flex;
        align-items: center;
        justify-content: center;

        &.active {
          color: var(--a-main-color);
          border: 2rpx solid var(--a-main-color);
        }
      }
    }

    .uploadImg {
      position: relative;
      box-sizing: border-box;
      height: 400rpx;
      background: var(--a-main-box-bg-color);
      border-radius: 20rpx;
      margin-top: 22rpx;
      padding: 16rpx 20rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;

      .imgSty {
        display: block;
        width: 100%;
        height: 100%;
        background-color: rgba($color: #FFF, $alpha: 0.2);
      }

      .upload_btn {
        text-align: center;

        .iconfont {
          display: block;
          font-size: 36rpx;
          color: var(--a-main-color);
        }

        .text {
          margin-top: 5rpx;
          font-size: 32rpx;
          color: var(--a-three-text-color);
        }

      }

      .imageProcessing_btn {
        position: absolute;
        right: 20rpx;
        bottom: 20rpx;
        width: 104rpx;
        height: 43rpx;
        background: #57547B;
        border-radius: 23rpx;
        border: 1rpx solid rgba(255, 255, 255, 0.6);
        font-size: 20rpx;
        color: var(--a-one-text-color);
        display: flex;
        align-items: center;
        justify-content: center;
      }

    }

    .uploadRefImg {
      box-sizing: border-box;
      width: 160rpx;
      height: 160rpx;
      border-radius: 20rpx;
      background: var(--a-main-box-bg-color);
      margin-top: 22rpx;
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      overflow: hidden;

      .imgSty {
        display: block;
        width: 100%;
        height: 100%;
        border-radius: 20rpx;
      }

      .upload_btn {
        text-align: center;

        .iconfont {
          display: block;
          font-size: 36rpx;
          color: var(--a-main-color);
        }
      }

      .delIcon_box {
        position: absolute;
        top: 0;
        right: 0;
        width: 60rpx;
        height: 60rpx;

        .delIcon {
          position: absolute;
          top: 0;
          right: 0;
          width: 40rpx;
          height: 40rpx;
          background-color: rgba(0, 0, 0, 0.3);
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 0 0 0 20rpx;
          box-shadow: 0 0 10rpx rgba(255, 255, 255, 0.3);

          .iconfont {
            font-size: 24rpx;
            color: #fff;
          }
        }
      }

    }

    .label_box {
      display: flex;
      align-items: center;
      gap: 30rpx;
      margin-top: 40rpx;

      .label {
        flex-shrink: 0;
        font-size: 26rpx;
        color: #FFFFFF;
      }

      .value {
        flex: 1;

        .sliderBtn {
          width: 50rpx;
          height: 50rpx;
          font-size: 26rpx;
          border-radius: 50%;
          color: #83CD88;
          background-color: #FFF;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
    }

    .sliderLabel {
      box-sizing: border-box;
      font-size: 22rpx;
      color: #D5D4DF;
      margin-top: 30rpx;
      padding-left: 250rpx;

    }

    .textarea_box {
      position: relative;
      margin-top: 43rpx;

      .ai_create_btn {
        position: absolute;
        right: 16rpx;
        bottom: 16rpx;
        z-index: 2;
        width: 104rpx;
        height: 43rpx;
        background: #57547B;
        border-radius: 23rpx;
        font-size: 20rpx;
        color: var(--a-one-text-color);
        border: 1rpx solid rgba(255, 255, 255, 0.6);
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 5rpx;

        .iconfont {
          font-size: 24rpx;
        }
      }
    }

    .imgNumList {
      margin-top: 22rpx;
      display: flex;
      align-items: center;
      gap: 18rpx;

      .imgNum_item {
        box-sizing: border-box;
        width: 84rpx;
        height: 84rpx;
        border-radius: 13rpx;
        color: var(--a-one-text-color);
        background: var(--a-main-box-bg-color);
        border: 4rpx solid transparent;
        display: flex;
        align-items: center;
        justify-content: center;

        &.active {
          color: var(--a-main-color);
          border: 4rpx solid var(--a-main-color);
        }
      }
    }
  }

  .footer {
    .footer_placeholder {
      height: 176rpx;
    }

    .footer_content {
      box-sizing: border-box;
      position: fixed;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 176rpx;
      background: var(--a-main-tabNav-bg-color);
      padding: 28rpx 30rpx 0;
    }
  }
}
</style>